package com.haiqu.haiqu_helper.controller;

import com.haiqu.haiqu_helper.model.JsonResult;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

/**
 * className: GlobalExceptionController
 * description: TODO
 * author: mj
 * date: 2019/9/198:38 PM
 **/
@ControllerAdvice
@ResponseBody
public class GlobalExceptionController {
	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public JsonResult normalEceptionErrorHandler(Exception ex) throws Exception {
		ex.printStackTrace();
		JsonResult jsonResult = new JsonResult();
		jsonResult.setMessage(ex.getMessage());
		jsonResult.setCode(JsonResult.STATUS_EXCEPTION);
		return jsonResult;
	}

	@ExceptionHandler(MethodArgumentNotValidException.class)
	@ResponseStatus(HttpStatus.OK)
	public JsonResult bindException(MethodArgumentNotValidException e) {
		BindingResult bindingResult = e.getBindingResult();

		StringBuffer errorMessage = new StringBuffer();

		for (FieldError fieldError : bindingResult.getFieldErrors()) {
			errorMessage .append(fieldError.getDefaultMessage() + ", ");
		}
		//  此处代码为项目内统一返回java类 这里不做该类展示
		JsonResult jsonResult = new JsonResult();
		jsonResult.setCode(JsonResult.STATUS_EXCEPTION);
		jsonResult.setMessage(errorMessage.toString());
		return jsonResult;
	}
}
